package cn.yanhu.kuwanapp.utils

import cn.yanhu.kuwanapp.bean.response.RespBindAlipayBean
import java.io.UnsupportedEncodingException
import java.net.URLEncoder
import java.util.*

/**
 *
 * 类描述：支付宝工具类
 * @author：woochen
 * create at：2021/8/7 7:21 PM
 */
object AlipayUtil {
     const val SDK_PAY_FLAG = 1
     const val SDK_AUTH_FLAG = 2

     fun buildAuthInfoMap(data: RespBindAlipayBean): Map<String, String>? {
        val keyValues: MutableMap<String, String> = HashMap()
        keyValues["apiname"] = data.apiname
        keyValues["app_id"] = data.app_id
        keyValues["app_name"] = data.app_name
        keyValues["auth_type"] = data.auth_type
        keyValues["biz_type"] = data.biz_type
        keyValues["methodname"] = data.method
        keyValues["pid"] = data.pid
        keyValues["product_id"] = data.product_id
        keyValues["scope"] = data.scope
        keyValues["sign_type"] = data.sign_type
        keyValues["target_id"] = data.target_id
        keyValues["sign"] = data.sign
        return keyValues
    }

    /**
     * 构造支付订单参数信息
     *
     * @param map 支付订单参数
     * @return
     */
     fun buildOrderParam(map: Map<String, String>): String? {
        val keys: List<String> = ArrayList(map.keys)
        val sb = StringBuilder()
        for (i in 0 until keys.size - 1) {
            val key = keys[i]
            val value = map[key]
            sb.append(buildKeyValue(key, value, true))
            sb.append("&")
        }
        val tailKey = keys[keys.size - 1]
        val tailValue = map[tailKey]
        sb.append(buildKeyValue(tailKey, tailValue, true))
        return sb.toString()
    }

    /**
     * 拼接键值对
     *
     * @param key
     * @param value
     * @param isEncode
     * @return
     */
    private fun buildKeyValue(key: String, value: String?, isEncode: Boolean): String? {
        val sb = java.lang.StringBuilder()
        sb.append(key)
        sb.append("=")
        if (isEncode) {
            try {
                sb.append(URLEncoder.encode(value, "UTF-8"))
            } catch (e: UnsupportedEncodingException) {
                sb.append(value)
            }
        } else {
            sb.append(value)
        }
        return sb.toString()
    }

}